<template>
  <div class="box">
    <div class="logo">
      <img src="@/assets/img/logo.png" alt="" />
    </div>
    <!-- 左右箭头 -->
    <div class="goAndBack">
      <i class="left el-icon-arrow-left" @click="$router.go(-1)"></i>
      <i class="right el-icon-arrow-right" @click="$router.go(1)"></i>
    </div>
    <!-- 搜索+弹窗 -->
    <el-popover
      popper-class="searchBox"
      placement="bottom"
      :title="searchType ? '热搜榜' : '搜索建议'"
      width="370"
      trigger="click"
      v-model="isSHow"
    >
      <el-input
        placeholder="冲冲冲~~"
        prefix-icon="el-icon-search"
        v-model="searchData"
        slot="reference"
        class="searchInput"
        @input="handleSearch"
      >
      </el-input>
      <div class="searchHot" v-if="searchType">
        <div
          class="searchHotItem"
          v-for="(item, index) in searchHotList"
          :key="index"
          @click="handleSearchCallback(item)"
        >
          <div class="index" :class="{ hotRed: index + 1 <= 3 }">
            {{ index + 1 }}
          </div>
          <div class="singInfo">
            <span class="name">{{ item.searchWord }}</span>
            <span class="show">{{ item.content }}</span>
          </div>
        </div>
      </div>
      <div class="searchSuggest" v-else>
        <div class="singleItem">
          <p class="single el-icon-headset">单曲</p>
          <p
            class="item"
            v-for="item in searchSuggest.songs"
            :key="item.id"
            @dblclick="handledbclick(item.id)"
          >
            {{ item.name }}
          </p>
        </div>
        <div class="singerItem">
          <p class="single el-icon-microphone">歌手</p>
          <p
            class="item"
            v-for="item in searchSuggest.artists"
            :key="item.id"
            @click="
              $router.push({
                path: '/index/singerDetail',
                query: { id: item.id }
              })
            "
          >
            {{ item.name }}
          </p>
        </div>
        <div class="albumItem">
          <p class="single el-icon-c-scale-to-original">专辑</p>
          <p
            class="item"
            v-for="item in searchSuggest.albums"
            :key="item.id"
            @click="
              $router.push({
                path: '/index/album',
                query: { id: item.id }
              })
            "
          >
            {{ item.name }}
          </p>
        </div>
        <div class="songListItem">
          <p class="single el-icon-star-off">歌单</p>
          <p
            class="item"
            v-for="item in searchSuggest.playlists"
            :key="item.id"
            @click="
              $router.push({
                path: '/index/musicDateil',
                query: { id: item.id }
              })
            "
          >
            {{ item.name }}
          </p>
        </div>
      </div>
    </el-popover>
    <!-- 头像登录 -->
    <div class="userBox">
      <div class="avator">
        <el-popover
          v-if="!userInfo?.avatarUrl"
          placement="bottom"
          width="400"
          trigger="click"
          v-model="isShowPopover"
        >
          <img src="@/assets/img/test.jpg" alt="" slot="reference" />
          <loginTab
            :isShowRegister.sync="isShowRegister"
            @getUserInfo="
              (info) => {
                ;(userInfo = info), (isShowPopover = false)
              }
            "
          ></loginTab>
        </el-popover>
        <img :src="userInfo.avatarUrl" alt="" v-else @click="goToPresonal" />
      </div>
      <div class="userName" v-if="userInfo?.nickname">
        {{ userInfo.nickname }}
      </div>
      <div class="login" v-else>← 请登录</div>
    </div>
    <!-- 注册弹窗 -->
    <regigter
      :isShowRegister="isShowRegister"
      @closeRegister="isShowRegister = false"
    ></regigter>
  </div>
</template>
<script>
import { getAccountInfo } from '@/api/login/login'
import { getSearchHotList, getSearchSuggestList } from '@/api/search/search'
import loginTab from '../login/loginTab.vue'
import regigter from '../login/components/registerPage.vue'
import { getMusicInfo } from '@/api/music/music'
import { handleMusicTime } from '@/plugins/utils'
export default {
  name: 'HeaderBar',
  data() {
    return {
      searchData: '', //搜索的值
      isShowPopover: false, //是否显示Popover弹窗
      userInfo: {}, // 用户信息
      isShowRegister: false, // 是否打开注册弹窗
      searchHotList: {}, // 搜索热榜列表
      searchSuggest: {}, // 搜索建议列表
      searchType: true, // 显示搜索热榜还是搜索建议
      timer: null, // 请求搜索建议列表防抖
      isSHow: false //打开搜索框
    }
  },
  components: {
    loginTab,
    regigter
  },
  async created() {
    if (this.$store.state.isLogin) {
      this.$store.commit('updataLoginState', false)
    }

    if (localStorage.getItem('userId')) {
      // 如果能获取到userId说明已经登录了
      this.getAccountInfo()

      this.$store.commit('updataLoginState', true)
      // console.log('尝试获取Userid', this.$store.state.isLogin)
      // console.log(this.userInfo)
    } else {
      console.log('没有尝试获取Userid', this.$store.state.isLogin)
      this.$store.commit('updataLoginState', false)
      if (localStorage.getItem('userId')) localStorage.removeItem('userId')
    }
    // 一进页面获取热榜
    this.getSearchHotList()
  },
  methods: {
    goToPresonal() {
      // console.log('去个人信息页')
      this.$router.push({
        path: '/index/personal',
        query: { id: localStorage.getItem('userId') }
      })
    },
    // 获取个人信息
    async getAccountInfo() {
      const res = await getAccountInfo()
      this.userInfo = res.data.profile
    },
    // 获取搜索热榜
    async getSearchHotList() {
      const res = await getSearchHotList()
      this.searchHotList = res.data.data
      // console.log(res.data.data)
    },
    // 获取搜索建议列表
    async getSearchSuggest(searchValue) {
      const res = await getSearchSuggestList(searchValue)
      this.searchSuggest = res.data.result
      // console.log(res.data.result)
    },
    // 搜索输入框输入触发
    handleSearch(e) {
      // 节流或者防抖 其中一个搞会了再写
      // 思路每次输入一个字母不触发，等待最后一个字符出入后再触发，申请数据 明天写
      // 2023/9/26 20:46
      // 得到数据渲染搜索建议列表，获得数据改变搜索框的搜索状态，显示，搜索热榜或者搜索建议
      clearTimeout(this.timer)
      if (e !== '') {
        this.timer = setTimeout(async () => {
          await this.getSearchSuggest(e)
          this.searchType = false
        }, 500)
      } else {
        this.searchSuggest = {}
        this.searchType = true
      }
    },
    // 点击热榜回调
    handleSearchCallback(item) {
      this.isSHow = !this.isSHow
      console.log(item.searchWord, '点击热榜')
      this.$router.push({
        path: '/index/search',
        query: { name: item.searchWord }
      })
    },
    // 双击播放搜索歌曲
    async handledbclick(id) {
      let row = await this.getMusic(id)
      // console.log(row)
      let musicList = this.$store.state.musicList
      let currentIndex = this.$store.state.currentIndex

      let findResult = musicList.find((el) => el.id === row.id)
      if (findResult) {
        this.$store.commit('updateMusicId', row.id)
      }
      console.log(currentIndex, findResult)
      musicList.splice(currentIndex + 1, 0, row)
      this.$store.commit('updateMusicId', row.id)
      this.$store.commit('updateMusicLits', {
        musicList,
        musicListId: this.$store.state.musicListId
      })
    },
    // 根据id获取歌曲信息
    async getMusic(id) {
      const res = await getMusicInfo(id)
      console.log(res)
      res.data.songs[0].dt = handleMusicTime(res.data.songs[0].dt)
      return res.data.songs[0]
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  align-items: center;
  background: #ec4141;
  height: 60px;
  // logo
  img {
    width: 140px;
    margin-left: 15px;
  }
  // 左右箭头
  .goAndBack {
    i::before {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 28px;
      height: 28px;
      background-color: rgba(0, 0, 0, 0.07);
      border-radius: 22px;
      color: #fff;
      font-size: 16px;
      margin: 0 5px;
      cursor: pointer;
    }
    .left {
      margin-left: 60px;
    }
  }
}
// 输入框样式
.searchInput {
  margin-left: 10px;
  :deep(.el-input__inner) {
    width: 170px;
    height: 35px;
    border-radius: 35px;
    border: none;
    background-color: rgba(0, 0, 0, 0.07);
    padding-left: 35px;
    color: #fff;
  }
  :deep(.el-input__icon) {
    color: #fff;
  }
  :deep(.el-input__inner::placeholder) {
    color: #fff;
  }
}
.userBox {
  position: absolute;
  top: 5px;
  right: 0;
  height: 50px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-right: 10px;
  color: #fff;
  .avator {
    img {
      width: 35px;
      border-radius: 35px;
      vertical-align: middle;
      cursor: pointer;
    }
  }
  // 登录
  .login {
    margin-left: 10px;
  }
  // 用户名
  .userName {
    margin: 0 20px;
  }
}
// 热搜榜

.searchHot {
  height: 475px;
  // overflow: scroll;

  .searchHotItem {
    display: flex;
    justify-content: first baseline;
    align-items: center;
    height: 60px;
    cursor: pointer;
    &:hover {
      background-color: #f2f2f2;
    }
    .index {
      padding: 0 8px;
      font-size: 18px;
      margin-left: 10px;
      // color: #ec4141;
    }
    .singInfo {
      display: flex;
      flex-direction: column;
      justify-content: center;
      margin-left: 10px;
      .name {
        font-size: 16px;
        font-weight: 700;
        color: #000;
      }
      .show {
        font-size: 14px;
      }
    }
  }
}
// 热榜前三红色
.hotRed {
  color: #ec4141;
}
// 搜索建议
.searchSuggest {
  div {
    font-size: 16px;
    cursor: pointer;
    .item {
      padding: 5px 0 5px 30px;
      font-size: 14px;
      &:hover {
        background-color: #f5f5f7;
      }
    }
    .single {
      width: 100%;
      height: 37px;
      line-height: 37px;
      padding-left: 15px;
      background-color: #f5f5f7;
    }
    :deep(.single::before) {
      margin-right: 5px;
      font-size: 16px;
    }
  }
}
</style>
